package com.zhiyu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.PageInfo;
import com.zhiyu.common.ApiReturn;
import com.zhiyu.config.AlipayConfig;
import com.zhiyu.util.OrderUtil;
import com.zhiyu.pojo.*;
import com.zhiyu.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RequestMapping("order")
@Controller
@CrossOrigin
public class OrderController {
    final static Logger log = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCarService shoppingCarService;
    @Autowired
    private ProductsService productsService;
    @Autowired
    private AddressService addressService;

    //订单管理
    @RequestMapping("ordersManage")
    @ResponseBody
    public ApiReturn ordersManage(Orders orders,HttpServletRequest request,HttpServletResponse response){
        PageInfo<Orders> page = ordersService.findPage(orders);
        page.getList().forEach( orders1 -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders1.getOrderId());
            orders1.setOdetailList(orderDetailService.findList(orderDetail));
        });
        if (page.getList()!=null){
            return ApiReturn.success("返回订单数据",page);
        }
        return ApiReturn.error("无数据");
    }

    //订单详情
    @RequestMapping("getOrderDetail")
    @ResponseBody
    public ApiReturn getOrderDetail(OrderDetail orderDetail){
        List<OrderDetail> orderDetailList= orderDetailService.findList(orderDetail);
        if (orderDetailList!=null&&orderDetailList.size()>0){
            return ApiReturn.success("返回订单详情数据",orderDetailList);
        }
        return ApiReturn.error("无数据");
    }

    //删除订单
    @RequestMapping("deleteOrder")
    @ResponseBody
    public ApiReturn deleteOrder(Orders orders){
        int count = ordersService.delete(orders);
        if (count<1){
            return ApiReturn.error("删除失败");
        }
        return ApiReturn.success("删除成功");
    }

    //用户支付
    @RequestMapping("pay")
    @ResponseBody
    public ApiReturn pay(String ids,HttpServletRequest request,HttpServletResponse response){
        String userInfo = (String) request.getSession().getAttribute("userInfo");
        String[] userStr = userInfo.split(":");
        String[] idList = ids.split(",");
        Address address = addressService.selectDefault(Integer.valueOf(userStr[0]));
        if (address == null ){
            return ApiReturn.error("用户没用默认地址");
        }
        List<ShoppingCar> shoppingCarList = shoppingCarService.selectByIds(idList);
        int num = 0;
        int total = 0;
        String orderNum = OrderUtil.getOrderNum();
        Orders orders = new Orders();
        orders.setOrderId(orderNum);
        orders.setStatus(0);
        orders.setOrderTime(new Date());
        orders.setUserId(Integer.valueOf(userStr[0]));
        for (ShoppingCar shoppingCar : shoppingCarList) {
            OrderDetail orderDetail = new OrderDetail();
            Products products = productsService.get(shoppingCar.getProId());
            orderDetail.setProQuantity(shoppingCar.getProQuantity());
            orderDetail.setProPrice(products.getProPrice());
            orderDetail.setProId(products.getProId());
            orderDetail.setOrderId(orderNum);
            orderDetailService.insert(orderDetail);
            num += shoppingCar.getProQuantity();
            total += shoppingCar.getProQuantity()*products.getProPrice().intValue();
            shoppingCarService.delete(shoppingCar);
        }
        orders.setProCount(num);
        orders.setTotalPrice(total);
        orders.setAddressId(address.getAddressId());
        ordersService.insert(orders);
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no =orderNum;
        //付款金额，必填
        String total_amount = String.valueOf(total);
        //订单名称，必填
        String subject = "为爱而购";
        //商品描述，可空
        String body = "鲜花";

        System.out.println("out_trade_no:" + out_trade_no);
        System.out.println("total_amount:" + total_amount);
        System.out.println("subject:" + subject);
        System.out.println("body:" + body);

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "15m";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();

        } catch (AlipayApiException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    //支付成功
    @RequestMapping("success")
    @ResponseBody
    public void success(String orderId) {
        ordersService.updateStatus(orderId);
    }
}
